/**
 * Welcome to Cloudflare Workers! This is your first worker.
 *
 * - Run `npm run dev` in your terminal to start a development server
 * - Open a browser tab at http://localhost:8787/ to see your worker in action
 * - Run `npm run deploy` to publish your worker
 *
 * Bind resources to your worker in `wrangler.jsonc`. After adding bindings, a type definition for the
 * `Env` object can be regenerated with `npm run cf-typegen`.
 *
 * Learn more at https://developers.cloudflare.com/workers/
 */
import { setupEnv } from './_env';
import { createResp } from './_utils';
import pkgFetch, { isPkgReq } from './pkg';

export default {
  async fetch(req, env, ctx): Promise<Response> {
    setupEnv(env);
    const url = new URL(req.url);
    const { json } = createResp();
    if (isPkgReq(req, url)) {
      return pkgFetch(req, url);
    }
    return json.stringify({ error: 'Invalid request' }, 404);
  },
} satisfies ExportedHandler<Env>;
